package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.swing.plaf.TableHeaderUI;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private StringRedisTemplate stringRedisTemplate;

    //创建调用Redis读取lua脚本方法的一个传参
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT ;
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        //设置脚本位置
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //设置返回值
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /*解决多个JVM线程id一致而相互可以删锁的问题*/
    private static final String ID_PREFIX = UUID.randomUUID().toString();

    private String name;

    private static final String KEY_PREFIX = "lock:";

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程指示
        /*String threadId = Thread.currentThread().getName();*/
        /*解决多个JVM 线程id相同而可以互相删锁的问题*/
        String threadId  = ID_PREFIX + Thread.currentThread().getName();
        String lockKey = KEY_PREFIX + name;
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,  threadId + "", timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }

    @Override
    public void unlock() {/*
        String lockKey = KEY_PREFIX + name;

        String threadId = ID_PREFIX + Thread.currentThread().getName() + "";
        //获取锁的标识
        String lockValue = stringRedisTemplate.opsForValue().get(lockKey);
        if(threadId .equals(lockValue)) {
            stringRedisTemplate.delete(name);
        }*/


        /*基于lua脚本实现删除分布式锁*/

        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX+name),ID_PREFIX + Thread.currentThread().getName()+"");

    }
}
